package org.kl.bf.web.basic;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.joda.time.DateTime;
import org.kl.bf.entity.basic.CalendarType;
import org.kl.bf.entity.basic.User;
import org.kl.bf.entity.easyui.EasyuiGrid;
import org.kl.bf.service.basic.CalendarService;
import org.kl.bf.service.basic.CalendarTypeService;
import org.kl.bf.utils.ExcelWriter;
import org.kl.bf.utils.KLServlets;
import org.kl.bf.web.base.BasicController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.utils.Collections3;
import org.springside.modules.web.MediaTypes;

@Controller
@RequestMapping(value = "/basic/calendarType")
public class CalendarTypeController extends BasicController {
	@Autowired
	private CalendarTypeService calendarTypeService;
	@Autowired
	private CalendarService calendarService;

	@RequiresPermissions("calendarType:list")
	@RequestMapping(method = RequestMethod.GET)
	public String list() {
		return "basic/calendarTypeList";
	}

	// @RequiresPermissions("calendarType:list")
	@RequestMapping(value = "dataGrid", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String dataGrid(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "rows", defaultValue = PAGE_SIZE) int pageSize,
			@RequestParam(value = "sort", defaultValue = "id") String sortType,
			@RequestParam(value = "order", defaultValue = "desc") String orderType, Model model, ServletRequest request) {
		Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
		searchParams.put("EQ_user.id", BasicController.getCurrentUserId());
		Page<CalendarType> calendarType = calendarTypeService.getUserCalendarType(searchParams, pageNumber, pageSize, sortType, orderType);
		EasyuiGrid grid = new EasyuiGrid();
		grid.setRows(calendarType.getContent());
		grid.setTotal((int) calendarType.getTotalElements());
		String result = jsonMapper.toJson(grid);
		return result;
	}

	// @RequiresPermissions("calendarType:update")
	@RequestMapping(value = "update", method = RequestMethod.POST, produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String update(@Valid @ModelAttribute("calendarType") CalendarType calendarType, RedirectAttributes redirectAttributes,
			HttpSession session) {
		if (StringUtils.isBlank(calendarType.getId())) {
			if (calendarTypeService.getCalendarTypeByUSerIdAndTypeName(BasicController.getCurrentUserId(), calendarType.getTypeName()) != null) {
				return ajaxMsg("编辑失败,该用户已存在该日程类型名称", false, null);
			}
		} else {
			if (calendarTypeService.getCalendarTypeByUSerIdAndTypeName(BasicController.getCurrentUserId(), calendarType.getTypeName()) != null
					&& !StringUtils.equals(
							calendarTypeService.getCalendarTypeByUSerIdAndTypeName(BasicController.getCurrentUserId(),
									calendarType.getTypeName()).getId(), calendarType.getId())) {
				return ajaxMsg("编辑失败,该用户已存在该日程类型名称", false, null);
			}
		}
		calendarType.setUser(new User(BasicController.getCurrentUserId()));
		try {
			calendarTypeService.saveCalendarType(calendarType);
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("编辑失败[" + e.getMessage() + "]", false, null);
		}
		List<CalendarType> calendarTypeList = calendarTypeService.getAllCalendarType();
		for (CalendarType c : calendarTypeList) {
			session.getServletContext().setAttribute(c.getId(), c.getTypeName());
		}
		return ajaxMsg("编辑成功", true, null);
	}

	@RequestMapping(value = "reque", method = RequestMethod.POST)
	@ResponseBody
	public String reque(@Valid @ModelAttribute("calendarType") CalendarType calendarType, RedirectAttributes redirectAttributes,
			HttpSession session) {
		List<CalendarType> calendarTypeList = calendarTypeService.getCalendarTypes(BasicController.getCurrentUserId());
		for (CalendarType c : calendarTypeList) {
			session.getServletContext().setAttribute(c.getId(), c.getTypeName());
		}
		return ajaxMsg("编辑成功", true, calendarTypeList);
	}

	// @RequiresPermissions("calendarType:delete")
	@RequestMapping(value = "delete/{id}", produces = MediaTypes.JAVASCRIPT_UTF_8, method = RequestMethod.POST)
	@ResponseBody
	public String delete(@PathVariable("id") String id, RedirectAttributes redirectAttributes, HttpSession session) {
		if (Collections3.isEmpty(calendarService.getCalendarListBytypeId(id, BasicController.getCurrentUserId()))) {
			calendarTypeService.deleteCalendarType(id);
			return ajaxMsg("删除成功", true, null);
		} else {
			return ajaxMsg("删除失败，存在相应日程类型的日程安排", false, null);
		}
	}

	// @RequiresPermissions("calendarType:delete")
	@RequestMapping(value = "multiDelete", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String multiDelete(@RequestParam(value = "ids", defaultValue = "") String ids) {
		String msg = "";
		try {
			msg = calendarTypeService.multiDelete(ids);
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("删除失败:" + e.getMessage(), false, null);
		}
		return ajaxMsg("删除成功:" + msg, true, null);
	}

	// @RequiresPermissions("calendarType:export")
	@RequestMapping(value = "excelExport", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String excelExport(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "sort", defaultValue = "id") String sortType,
			@RequestParam(value = "order", defaultValue = "desc") String orderType, Model model, ServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
		Page<CalendarType> calendarTypes = calendarTypeService.getUserCalendarType(searchParams, pageNumber, 0, sortType, orderType);
		try {
			// 输出Excel文件.
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Content-Disposition",
					"attachment;filename=\""
							+ new String(("员工信息" + new DateTime().toString("yyyyMMddHHmmss") + ".xls").getBytes("gb2312"), "ISO8859-1")
							+ "\"");
			ExcelWriter.exportExcel("员工信息", CalendarType.class, calendarTypes.getContent(), response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				response.getOutputStream().flush();
				response.getOutputStream().close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 所有RequestMapping方法调用前的Model准备方法, 实现Struts2
	 * Preparable二次部分绑定的效果,先根据form的id从数据库查出Task对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此仅在update时实际执行.
	 */
	@ModelAttribute
	public void getCalendarType(@RequestParam(value = "id", defaultValue = "-1") String id, Model model) {
		if (!id.equals("-1")) {
			model.addAttribute("calendarType", calendarTypeService.getCalendarType(id));
		}
	}
}
